package com.turing.data.scripts.contract.filter

import com.turing.data.engine.Group
import com.turing.data.engine.TextUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils
import org.springframework.util.CollectionUtils
import com.turing.common.util.FileUtils

/**
 * 场景：资产管理合同
 * 版本：Version 1
 * 要素名称：标准化
 */

class Standardizing_30191_10_filter {

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams) {

        List<TaskElementVO.DrawResultVO> result = new ArrayList<>()

        def valueMap = [
                        "银行存款":["银行存款","存款"],
                        "结构性存款":["结构性存款"],
                        "同业存单":["同业存单"],
                        "证券交易所债券":["国债"],
                        "银行间市场债券":["国债"],
                        "可交换债":["可交换债","可交债","可交换公司债"],
                        "可转债":["可转债","可转换债券","可转换债","可转换公司债"],
                        "央行票据":["央行票据"],
                        "短期融资券":["短期融资券"],
                        "中期票据":["中期票据"],
                        "资产支持证券":["资产支持证券","ABS"],
                        "非金融企业债务融资工具":["非金融企业债务融资工具"],
                        "股票一级":["股票一级","股票一级、二级","沪深交易所A股（含一级市场）"],
                        "股票定增":["股票定增","定增","定向增发"],
                        "股票二级":["股票二级","股票一级、二级","沪深交易所A股（含一级市场）"],
                        "优先股":["优先股"],
                        "港股通":["沪港通","深港通"],
                        "新三板股票":["新三板股票","新三板"],
                        "股指期货":["股指期货"],
                        "国债期货":["国债期货"],
                        "商品期货":["商品期货"],
                        "场内期权":["场内期权"],
                        "公募基金份额（不含货币基金）":["股票型基金","债券型基金","混合型基金","证券投资基金"],
                        "货币基金":["货币基金","货币型基金","证券投资基金"],
                        "债券正回购":["债券正回购","债券回购","回购"],
                        "债券逆回购":["债券逆回购","债券回购","回购"],
                        "融资融券":["融资融券","两融"],
                        "存托凭证":["存托凭证"],
                        "其他":["利率互换"]
                        ]

        def valueList = ["银行存款", "存款", "结构性存款", "同业存单", "国债", "可交换债", "可交债",
                                "可转债", "可转换债券", "可转换债", "央行票据", "短期融资券", "中期票据",
                                "资产支持证券", "ABS", "非金融企业债务融资工具", "股票一级", "一级", "股票定增",
                                "定增", "定向增发", "股票二级", "二级", "优先股", "沪港通", "深港通", "新三板股票",
                                "新三板", "股指期货", "国债期货", "商品期货", "场内期权", "股票型基金", "债券型基金",
                                "混合型基金", "货币基金", "货币型基金", "债券正回购",
                                "债券逆回购", "回购", "融资融券", "两融", "存托凭证", "利率互换",
                                "沪深交易所A股（含一级市场）", "中央银行票据","可转换公司债","可交换公司债","所有证券投资基金"]
        def REGEX_EXCLUDE = "具体投资范围详见"
        def relatedObjects = dependParams.relatedObjects
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        if (null == relatedObjects || relatedObjects.size() == 0) {
            if (!CollectionUtils.isEmpty(resultVOs) && resultVOs.size() > 2) {
                result.add(resultVOs[0])
                result.add(resultVOs[1])
                return result
            }
            return resultVOs
        }

        def relatedObject = relatedObjects.get("合同规定的主要投资范围及投资组合比例")
        def text = relatedObject.text

//        if (relatedObject == null || relatedObject.text == null || relatedObject.text == "" || relatedObject.childTaskSn == null) {
        if (true) {
            // 标准化的模型要素比较准，直接用模型要素来扩张
            try {
                for (resultVO in resultVOs) {
                    def text0 = resultVO.text.replaceAll("\n", "")
                    def rawText = FileUtils.loadJson(dependParams.textPathMap.get(resultVO.childTaskSn))//纯文本
                    def fileTextStr = dependParams.JSONTextMap.get(resultVO.childTaskSn)//json文本
                    def expandL = 0, expandR = 0, start = resultVO.start, end = resultVO.end
                    boolean findHead = false
                    while (expandL < 800 && start > expandL) {
//                        println "expandL is "+expandL + ", start is " + start
                        def expandStr = rawText.substring(start - expandL, end)//在全文中向前找
                        if (expandStr =~ "投资范围及比例" || expandStr =~ "投资范围及投资比例"
                                || expandStr =~ "投资范围如下" || expandStr =~ "．投资范围"
                                || expandStr =~ "本计划投资范围为符合") {//向前找到 投资范围 为止
                            def expandStrExt = rawText.substring(start - expandL - 80, end)
                            if(expandStrExt =~ REGEX_EXCLUDE){
                                break
                            }
//                            println "找到投资范围，skip"
                            findHead = true
                            break
                        }
                        expandL++
                    }

                    def REGEX_STOP = /.*比例.*%。/
                    def REGEX_STOP_1 = /.*比例.*%\./
                    def REGEX_STOP_3 = /.*比例.*%（.*。./
                    def REGEX_STOP_4 = /.*比例.*‰。./
                    if (findHead) {
                        while (expandR < 1000 && rawText.length() > expandR + end) {
//                        println "rawText length is " + rawText.length() + ", expandR + end is " + (expandR + end) + "，expandR is " + expandR
                            def expandString = rawText.substring(start - expandL, end + expandR)//在全文中向后找
                            if (expandString =~ REGEX_STOP || expandString =~ REGEX_STOP_1 || expandString =~ REGEX_STOP_3 || expandString =~ REGEX_STOP_4 ) {//向后找到 比例 为止
                                def text1 = rawText.substring(start - expandL, end + expandR)//原值向后找到比例的值
                                for ( s in valueMap.keySet()) {
                                    def valueL = valueMap.get(s)
                                    for (value in valueL) {
                                        if (text1.contains(value)) {
                                            def index = text1.indexOf(value)
                                            if ((text1.length() > (index + 1)
                                                    && (text1.substring(index - 1, index).contains("、")
                                                    || text1.substring(index - 1, index).contains("，")
                                                    || text1.substring(index - 1, index).contains("。")
//                                                    || text0.substring(index - 1, index).contains("：")
                                                    || text1.substring(index - 1, index).contains("（")))//value前边的一个符号是否为、.。（

                                                    || (text1.length() > (index + 1 + value.length())
                                                    && (text1.substring(index + value.length(), index + 1 + value.length()).contains("、")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains("，")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains(",")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains("。")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains(";")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains("（")
                                                    || text1.substring(index + value.length(), index + 1 + value.length()).contains("）")))) {//value后边的一个符号是否为、.。）
                                                def startOffset = index - expandL
                                                def endOffset = -(text0.length() + expandL - index - value.length())
                                                TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(resultVO)
                                                objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText)
//                                                    objectNew.text = rawText.substring(startOffset, endOffset)
                                                objectNew.businessValue = s
//                                                    objectNew.type = 1
                                                result.add(objectNew)
                                                break
                                            }
//                                            break
                                        }
                                    }
                                }
//                            println "找到比例，跳出"
                                break
                            }
                            expandR++
                        }
                    }


//
                    if (!CollectionUtils.isEmpty(result)) {
                        break
                    }
                }
                if (CollectionUtils.isEmpty(result)) {
                    return resultVOs
                } else {
                    result = Group.removeDuplicated(result)
                    result = Group.sortByPosition(result)
                }
                return result
            } catch (Exception e) {
                e.printStackTrace()
            }
        }

        // 如果标准化的模型要素找不到，再用关联的《投资范围比例》要素值来找
        def textPathMap = dependParams.textPathMap
        def rawPath = textPathMap.get(relatedObject.childTaskSn)
        def rawText = FileUtils.loadJson(rawPath)
        def JSONTextMap = dependParams.JSONTextMap
        def fileTextStr = ""
        fileTextStr = JSONTextMap.get(relatedObject.childTaskSn)
        text = text.replaceAll("\n", "")
        for (value in valueList) {
            if (text.contains(value)) {
                int index = text.indexOf(value)
                try {
                    if (text.substring(index - 1, index).contains("、") || text.substring(index - 1, index).contains("，")
                            || text.substring(index - 1, index).contains("。") || text.substring(index - 1, index).contains("（")
                            || text.substring(index + value.length(), index + 1 + value.length()).contains("、")
                            || text.substring(index + value.length(), index + 1 + value.length()).contains("，")
                            || text.substring(index + value.length(), index + 1 + value.length()).contains("。")
                            || text.substring(index + value.length(), index + 1 + value.length()).contains(":")
                            || text.substring(index + value.length(), index + 1 + value.length()).contains("）")) {
                        def startOffset = index
                        def endOffset = -(text.length()  - index - value.length())
                        TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(relatedObject)
                        objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText)
                        objectNew.text = value
                        result.add(objectNew)
                    }
                } catch (Exception e) {
                    e.printStackTrace()
                }
            }
        }

        try {
            if (result.size() == 0) {
                return resultVOs
            } else {
                result = Group.removeDuplicated(result)
                result = Group.sortByPosition(result)
            }
        } catch (Exception e) {
            e.printStackTrace()
        }
        return result
    }

}
